<template>
  <el-dialog
    v-el-drag-dialog
    title="签单"
    :visible.sync="visible"
    width="1366px"
    @closed="reset"
  >
    <el-form ref="dataForm" inline :model="temp" :rules="rules">
      <el-descriptions size="medium" :column="2" style="margin-bottom: 20px;">
        <el-descriptions-item label="客户编号">{{ order.csmCode }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ order.csmName }}</el-descriptions-item>
        <el-descriptions-item label="客户地址">{{
          order.csmAddress
        }}</el-descriptions-item>
      </el-descriptions>
      <el-form-item label="责任机构:" prop="orgSNNo">
        <el-tree-select
          v-model="temp.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="处理人:" prop="userId">
        <el-select v-model="temp.userId" style="width: 100%;" filterable placeholder="请选择">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式:" prop="paymentMethod">
        <el-select
          v-model="temp.paymentMethod"
          :disabled="payMethodDisabled"
          placeholder="请选择"
          style="width: 150px;"
          @change="paymentChange"
        >
          <el-option
            v-for="item in paymentMethodMapClone"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <lb-table
      ref="lbTable"
      class="table"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      :immediate-fetch="false"
      :summary-method="getSummaries"
      show-summary
      @fetch="fetchData"
    />

    <el-descriptions
      size="medium"
      :column="4"
      style="margin-top: 20px;"
      :label-style="{ color: '#F24024' }"
      :content-style="{ color: '#F24024' }"
    >
      <el-descriptions-item label="总应收">{{ totalTreceivable }}</el-descriptions-item>
      <el-descriptions-item label="总实收">{{ totalReflections }}</el-descriptions-item>
      <el-descriptions-item
        v-if="tableData.data.some((item) => item.pricingMode === 2)"
        label="总送出重量"
      >{{ totalGasWeight }}</el-descriptions-item>
      <el-descriptions-item
        v-if="tableData.data.some((item) => item.pricingMode === 2)"
        label="总回收重量"
      >{{ totalFee3 }}</el-descriptions-item>
    </el-descriptions>
    <div slot="footer" class="dialog-footer">
      <el-checkbox
        v-model="checked"
        style="float: left;"
      >液化气商品签收数量等于扫重瓶数量</el-checkbox>
      <el-button @click="visible = false"> 取消 </el-button>
      <el-button :loading="$loadingPlugin.success" type="primary" @click="success">
        确认签收
      </el-button>
    </div>
    <prepaid-card ref="prepaidCard" />
  </el-dialog>
</template>

<script>
  import {
    querySignOrderOrderBillData,
    queryCsmCardCodeByOrderCode,
    submitSignOrder,
    queryOwnerList,
    csDeliverUserList,
    queryShowCsmCardDetail,
    selectMonthBalanceByOrderCode,
    removePaymentMethod
  } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import PrepaidCard from './PrepaidCard'
  import { formatColumnMap } from '@/utils'

  export default {
    name: 'sign-order',
    components: {
      PrepaidCard
    },
    props: {
      transactorList: {
        type: Array,
        required: true
      },
      paymentMethodMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        currentOrg: null,
        ownersList: [],
        treeData: [],
        specList: [],
        showCsmCard: false, // 是否显示预付卡
        check_csmCard_ok_info: {
          check_csmCard_ok_status: false, // 是否校验通过预付卡密码或验证码 true表示校验通过 false表示校验失败
          check_csmCard_ok_msg: ''
        },
        check_month_ok_info: {
          check_month_ok_status: false, // 是否校验通过预付卡密码或验证码 true表示校验通过 false表示校验失败
          check_month_ok_msg: ''
        },
        paymentMethodMapClone: [],
        csmName: '',
        csmPhone: '',
        temp: {
          orgSNNo: '',
          userId: '',
          paymentMethod: 1
        },
        payMethodDisabled: false,
        row: {},
        detail: {},
        order: {},
        checked: false, // 是否勾选液化气商品签收数量等于扫重瓶数量
        sums: [], // 合计行的数据  表单提交验证
        tableData: {
          column: [
            {
              type: 'index'
            },
            {
              prop: 'goodsName',
              width: 115,
              label: '商品名称'
            },
            {
              prop: 'specCode',
              label: '规格型号',
              width: 115,
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit && scope.row.pricingMode === 2 ? (
                    <el-select
                      value={scope.row[scope.column.property]}
                      onChange={(val) => {
                        scope.row[scope.column.property] = val
                      }}
                    >
                      {this.specList.map((option) => {
                        return (
                          <el-option
                            label={option.specName}
                            value={option.specCode}
                          ></el-option>
                        )
                      })}
                    </el-select>
                  ) : (
                    <span>
                      {formatColumnMap(
                        this.specList,
                        'specCode',
                        scope.row[scope.column.property],
                        'specName'
                      )}
                    </span>
                  )}
                </div>
                )
              }
            },
            {
              prop: 'gcount',
              align: 'right',
              label: '数量',
              render: (h, scope) =>
                scope.row._edit && scope.row.pricingMode === 2 ? (
                <el-input
                  v-model={scope.row[scope.column.property]}
                  onInput={(val) =>
                    (scope.row[scope.column.property] = val.replace(/[^\d]/g, ''))
                  }
                  size='mini'
                />
                  ) : (
                <span>{scope.row[scope.column.property]}</span>
              )
            },
            {
              prop: 'gasWeight',
              width: 90,
              align: 'right',
              label: '送出重量',
              render: (h, scope) =>
                scope.row._edit && scope.row.pricingMode === 2 ? (
                <el-input-number
                  v-model={scope.row[scope.column.property]}
                  controls={false}
                  min={0}
                  max={9999}
                  precision={2}
                  onInput={(val) => (scope.row[scope.column.property] = val)}
                  size='mini'
                />
                  ) : (
                <span class='right'>{scope.row[scope.column.property]}</span>
              )
            },
            {
              prop: 'fee3',
              align: 'right',
              width: 90,
              label: '回收重量',
              render: (h, scope) =>
                scope.row._edit && scope.row.pricingMode === 2 ? (
                <el-input-number
                  v-model={scope.row[scope.column.property]}
                  controls={false}
                  min={0}
                  max={9999}
                  precision={2}
                  onInput={(val) => (scope.row[scope.column.property] = val)}
                  size='mini'
                />
                  ) : (
                <span class='right'>{scope.row[scope.column.property]}</span>
              )
            },
            {
              prop: 'netWeight',
              align: 'right',
              label: '净重',
              formatter: (row) => (row.netWeight ? row.netWeight : '0.00')
            },
            {
              prop: 'gprince',
              align: 'right',
              label: '单价'
            },
            {
              prop: 'gprefPrice',
              align: 'right',
              label: '优惠价格'
            },
            {
              prop: 'fee1',
              align: 'right',
              label: '远距配送费'
            },
            {
              prop: 'fee2',
              align: 'right',
              label: '上楼费'
            },
            {
              prop: 'tip',
              align: 'right',
              label: '服务费'
            },
            {
              prop: 'treceivable',
              align: 'right',
              label: '总应收',
              render: (h, { row }) => (
              <span>{row.treceivable ? Number(row.treceivable).toFixed(2) : '0.00'}</span>
            )
            },
            {
              prop: 'accReceivable',
              align: 'right',
              width: 100,
              label: '实收金额',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input
                      value={scope.row[scope.column.property]}
                      maxlength='8'
                      onInput={(val) => {
                        scope.row[scope.column.property] = val
                          .replace(/[^\d.]/g, '')
                          .replace(/^0\d+|^\./g, '')
                          .replace(/\.{2,}/g, '.')
                          .replace('.', '$#$')
                          .replace(/\./g, '')
                          .replace('$#$', '.')
                          .replace(/^(.*\..{2}).*$/, '$1')
                      }}
                    ></el-input>
                  ) : (
                    <span>
                      {scope.row[scope.column.property]
                        ? Number(scope.row[scope.column.property]).toFixed(2)
                        : ''}
                    </span>
                  )}
                </div>
                )
              }
            },
            {
              label: '操作',
              width: 80,
              alignt: 'center',
              fixed: 'right',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <div>
                      <el-link
                        underline={false}
                        onClick={() => {
                          this.handleSave(scope)
                        }}
                      >
                        保存
                      </el-link>
                      <el-link
                        underline={false}
                        type='danger'
                        onClick={() => {
                          this.handleCancle(scope)
                        }}
                      >
                        取消
                      </el-link>
                    </div>
                  ) : (
                    <el-link
                      underline={false}
                      onClick={() => {
                        this.handleEdit(scope)
                      }}
                    >
                      编辑
                    </el-link>
                  )}
                </div>
                )
              }
            }
          ],
          data: [],
          defaultData: []
        },
        rules: {
          userId: [
            { required: true, message: '请选择处理人', trigger: 'change' }
          ],
          paymentMethod: [
            { required: true, message: '请选择支付方式', trigger: 'change' }
          ]
        }
      }
    },
    computed: {
      ...mapGetters(['orgList', 'corpSettingData']),
      // 总应收
      totalTreceivable: function() {
        let count = 0
        if (this.tableData.data.length > 0) count = this.tableData.data.reduce((prev, cur) => prev + Number(cur.treceivable), 0)
        return isNaN(count) ? '0.00' : count.toFixed(2)
      },
      // 总实收
      totalReflections: function() {
        let count = 0
        if (this.tableData.data.length > 0) {
          count = this.tableData.data.reduce(
            (prev, cur) => prev + Number(cur.accReceivable || 0),
            0
          )
        }
        return isNaN(count) ? '0.00' : count.toFixed(2)
      },
      // 总送出重量
      totalGasWeight: function() {
        let count = 0
        if (this.tableData.data.length > 0) {
          count = this.tableData.data.reduce(
            (prev, cur) => prev + Number(cur.netWeight) + Number(cur.fee3),
            0
          )
        }
        return isNaN(count) ? '0.00' : count.toFixed(2)
      },
      // 总回收重量
      totalFee3: function() {
        let count = 0
        if (this.tableData.data.length > 0) { count = this.tableData.data.reduce((prev, cur) => prev + Number(cur.fee3), 0) }
        return isNaN(count) ? '0.00' : count.toFixed(2)
      }
    },
    methods: {
      async open(temp) {
        if (temp) {
          this.row = temp
          // await this.getOwnerList(temp.orgId)
          await this.getOwnersListNew(temp.orgId)
        }
        this.paymentMethodMapClone = JSON.parse(JSON.stringify(this.paymentMethodMap))
        await Promise.all([this.getTreeData(), this.getShowCsmCardValue()])
        this.init()
        return new Promise((resolve) => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp)
            const owner = this.ownersList.find(item => item.userId === temp.ownerId)
            if (owner) this.temp.userId = owner.userId
            else this.temp.userId = ''
            this.temp.orgSNNo = temp.orgSNNo
            this.detail = temp
            this.csmName = temp.csmName
            this.csmPhone = temp.csmPhone
            if ([2, 32, 64, 128, 512, 1024].includes(temp.paymentMethod)) {
              this.payMethodDisabled = true
            }
            this.removePaymentMethod()
            this.$nextTick(() => {
              this.$refs.lbTable.fetch({ currentPage: 1 })
            })
          }
        })
      },
      async getOwnerList(id) {
        const b = (this.corpSettingData.sp1 >> 2) & 0x01
        const orgId = id || this.currentOrg.orgId
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownersList = res.data
      },
      // 查询处理人列表（新）
      async getOwnersListNew(orgId) {
        const res = await csDeliverUserList({ deliveryOrgId: orgId })
        this.ownersList = res.data.filter(item => item.userId !== this.ownerId)
      },
      // 查询是否显示预付卡
      async getShowCsmCardValue() {
        const idx = this.paymentMethodMapClone.findIndex((item) => item.value === 8)
        this.paymentMethodMapClone.splice(idx, 1) // 支付方式下拉框去掉优惠券
        const res = await queryShowCsmCardDetail({
          orderCode: this.temp.orderCode
        })
        this.showCsmCard = res.data.showCsmCard
        this.specList = JSON.parse(res.data.specList)
        if (!this.showCsmCard) {
          const index = this.paymentMethodMapClone.findIndex((item) => item.value === 256)
          this.paymentMethodMapClone.splice(index, 1) // 删除预付卡
        }
      },
      async removePaymentMethod() {
        const res = await removePaymentMethod({ csmId: this.row.csmId, orgId: this.temp.orgId })
        if (res.data && res.data.length > 0) {
          const removeArr = res.data
          const paymentMethodMap = JSON.parse(JSON.stringify(this.paymentMethodMap))
          removeArr.forEach((item) => {
            const idx = paymentMethodMap.findIndex(item2 => item2.value === item)
            if (idx > -1) {
              paymentMethodMap.splice(idx, 1)
            }
          })
          this.paymentMethodMapClone = paymentMethodMap
          const values = this.paymentMethodMapClone.map(item => item.value)
          if (values.indexOf(this.temp.paymentMethod) === -1) {
            this.temp.paymentMethod = ''
          }
        } else {
          this.paymentMethodMapClone = JSON.parse(JSON.stringify(this.paymentMethodMap))
          const values = this.paymentMethodMapClone.map(item => item.value)
          if (values.indexOf(this.temp.paymentMethod) === -1) {
            this.temp.paymentMethod = ''
          }
        }
      },
      init() {
        const data = this.paymentMethodMap
        let text = ''
        const values = []
        for (let i = 0; i < data.length; i++) {
          var item = data[i]
          if (item.value === -1) {
            continue
          }
          if (item.value & this.row.paymentMethod) {
            if (!text) {
              text += item.text
            } else {
              text += ','
              text += item.text
            }
            values.push(item.value)
          }
        }

        if (values.length === 1) {
          this.$set(this.temp, 'paymentMethod', this.row.paymentMethod)
          if (
            values[0] === 2 ||
            values[0] === 32 ||
            values[0] === 64 ||
            values[0] === 128 ||
            values[0] === 512 ||
            values[0] === 1024
          ) {
            this.payDisabled = true
          }
        }
      },
      // 支付方式改变
      async paymentChange(value) {
        console.log(value)
        // 支付方式修改,则重置预付卡验证状态
        this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_status', false)
        this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_msg', '')
        this.$set(this.check_month_ok_info, 'check_month_ok_status', false)
        this.$set(this.check_month_ok_info, 'check_month_ok_msg', '')
        if (value === 16) {
          this.selectMonthBalanceByOrder()
        }
        // 预支付并且之前订单不是预付卡支付
        if (value === 256 && this.order.paymentMethod !== 256) {
          // 结束编辑
          const copy = JSON.parse(JSON.stringify(this.tableData.data))
          for (let i = 0; i < copy.length; i++) {
            if (copy[i].pricingMode === 2) {
              if (!copy[i].gasWeight || copy[i].gasWeight * 1 <= 0) {
                this.$message.warning(`请填写${copy[i].goodsName}的送出重量`)
                return
              }
              if (copy[i].accReceivable === '' || copy[i].accReceivable == null) {
                this.$message.warning(`请填写${copy[i].goodsName}的实收金额`)
                return
              }
              if (!copy[i].specCode) {
                this.$message.warning('请选择规格')
                return
              }
            }
          }
          copy.forEach((item) => {
            item._edit = false
          })
          this.$set(this.tableData, 'data', copy)
          // if (this.tableData.data.some(item => item._edit)) {
          //   this.$message.warning('请结束编辑！')
          //   return
          // }
          // 校验预支付账号是否存在,预支付金额是否足够支付
          this.selectCsmCardCodeByOrderCode()
        }
      },
      // 根据订单查询客户预付卡
      async selectCsmCardCodeByOrderCode() {
        const res = await queryCsmCardCodeByOrderCode({
          orderCode: this.detail.orderCode,
          billType: 1,
          payMoney: this.totalReflections
        })
        // 客户可用预付卡卡号
        const checkWay = res.data.accCsmCardConfigInfo.checkWay
        // 规则配置不是无校验
        if (checkWay !== 1 && this.detail.payStatus !== 3) {
          // 打开预付卡弹框
          this.$set(this.$loadingPlugin, 'success', false)
          const prepaidRes = await this.$refs.prepaidCard.open(res.data)
          // 预付卡密码或验证码验证通过
          if (prepaidRes) {
            this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_status', true)
            this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_msg', '')
          }
        } else {
          this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_status', true)
          this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_msg', '')
        }
      },
      // 根据订单查询客户月结
      async selectMonthBalanceByOrder() {
        const res = await selectMonthBalanceByOrderCode({ orderCode: this.temp.orderCode })
        const decimalSpare2 = res.data.decimalSpare2
        const settlementUseMonery = res.data.settlementUseMonery
        if (res.data.settlementType !== 2) {
          this.$message.error('用户不支持月结方式')
          return false
        }
        if (!Number(decimalSpare2)) {
          this.$message.error('没有设置月结授信额度')
          return false
        }
        if (this.order.paymentMethod !== 16) {
          if (Number(decimalSpare2) < (Number(settlementUseMonery) + Number(this.totalReflections))) {
            this.$message.error('月结额度不够，请使用其他支付方式')
            return false
          }
        } else {
          if (Number(decimalSpare2) < Number(settlementUseMonery)) {
            this.$message.error('月结额度不够，请使用其他支付方式')
            return false
          }
        }
        this.$set(this.check_month_ok_info, 'check_month_ok_status', true)
        this.$set(this.check_month_ok_info, 'check_month_ok_msg', '')
      },
      // 获取责任机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 获取详情数据
      async fetchData() {
        const res = await querySignOrderOrderBillData({ orderCode: this.temp.orderCode })
        this.order = res.data
        this.order.treceivables = res.data.treceivables
        this.tableData.data = res.data.detailList
        this.tableData.defaultData = JSON.parse(JSON.stringify(this.tableData.data))
        if (this.order.payStatus === 1) {
          let hasPricingMode2 = false // 是否有按单位计价的商品
          for (let i = 0; i < res.data.detailList.length; i++) {
            if (res.data.detailList[i].pricingMode === 2) {
              hasPricingMode2 = true
            }
            const detail = res.data.detailList[i]
            // 净气未完成的，实收为空;普通商品实收默认应收
            if (this.order.orderStatus !== 10 && detail.pricingMode === 2) {
              detail.accReceivable = null
            } else {
              detail.accReceivable = detail.treceivable
            }
            detail.gasWeight = (detail.fee3 || 0) + (detail.netWeight || 0)
            if (detail.gasWeight === 0) {
              detail.gasWeight = undefined
            }
          }
          if (hasPricingMode2 === false) {
            this.order.taccReceivable = this.order.treceivables
          }
        }
      },
      async success() {
        if (this.tableData.data.some((item) => item._edit)) {
          this.$message.error('请结束编辑！')
          return
        }
        var rows = this.tableData.data
        for (var i = 0; i < rows.length; i++) {
          if (rows[i].pricingMode === 2) {
            if (!rows[i].gasWeight || rows[i].gasWeight * 1 <= 0) {
              this.$message.warning(`请填写${rows[i].goodsName}的送出重量`)
              return
            }
            if (rows[i].accReceivable === '' || rows[i].accReceivable == null) {
              this.$message.warning(`请填写${rows[i].goodsName}的实收金额`)
              return
            }
            if (!rows[i].specCode) {
              this.$message.warning('请选择规格')
              return
            }
          }
        }
        var footerRow = {}
        this.sums.forEach((l, i) => {
          footerRow[ this.tableData.column[i].prop] = l
        })
        if (footerRow.fee3 * 1 < 0) {
          this.$message.error('回收重量需大于等于0')
          return
        }

        if (footerRow.netWeight * 1 < 0) {
          this.$message.error('净重需大于等于0')
          return
        }
        if (this.temp.paymentMethod === 256) {
          await this.selectCsmCardCodeByOrderCode()
        }
        let pass = true
        if (this.temp.paymentMethod === 16) { // 月结情况，判断额度是否够用
          await this.selectMonthBalanceByOrder().then(res => {
            // console.log(res)
            if (res !== undefined) {
              pass = res
              console.log(pass)
            }
          })
        }
        if (!pass) {
          return
        }
        this.$refs.dataForm.validate((valid) => {
          if (!valid) return
          const rows = this.tableData.data
          for (let i = 0; i < this.paymentMethodMap.length; i++) {
            // 支付方式存在预支付
            if (this.order.payStatus !== 3 && this.temp.paymentMethod === 256) {
              if (!this.check_csmCard_ok_info.check_csmCard_ok_status) {
                if (this.check_csmCard_ok_info.check_csmCard_ok_msg === '') {
                  this.$message.warning('使用预支付需要校验密码或验证码')
                  return
                } else {
                  this.$message.warning(
                    `${this.check_csmCard_ok_info.check_csmCard_ok_msg}`
                  )
                  return
                }
              }
            }
          }
          const matchOrg = this.orgList.find((item) => item.orgSNNo === this.temp.orgSNNo)
          const matchUser = this.ownersList.find(
            (item) => item.userId === this.temp.userId
          )
          const params = {
            paymentMethod: this.temp.paymentMethod,
            tReceivables: this.order.tReceivables,
            taccReceivable: this.totalReflections,
            orgId: matchOrg.orgId,
            orgName: matchOrg.orgName,
            orgSNNo: matchOrg.orgSNNo,
            ownerId: matchUser.userId,
            ownerName: matchUser.userName,
            ownerCode: matchUser.userCode,
            orderCode: this.order.orderCode,
            relBackGas: this.order.relBackGas,
            generalGas: this.order.generalGas,
            equalsWeightNum: this.checked ? 1 : 0,
            detailList: rows
          }
          this.$confirm(`实收金额:${params.taccReceivable}，确认提交吗？`, '提示', {
            type: 'warning'
          }).then(() => {
            const loading = this.$message({
              message: '正在提交',
              duration: 0,
              iconClass: 'el-icon-loading'
            })
            submitSignOrder(params)
              .then(() => {
                this.resolve()
                this.visible = false
                this.$notify({
                  title: '提示',
                  message: '操作成功',
                  type: 'success',
                  duration: 2000
                })
              })
              .finally(() => {
                loading.close()
              })
          })
        })
      },
      handleEdit(scope) {
        this.$set(scope.row, '_edit', true)
      },
      handleSave(scope) {
        scope.row.netWeight = (
          (scope.row.gasWeight || 0) * 1 -
          (scope.row.fee3 || 0) * 1
        ).toFixed(2)
        let treceivable = 0
        if (scope.row.pricingMode === 2) {
          treceivable =
            (scope.row.gprince - (scope.row.gprefPrice || 0) * 1) *
            ((scope.row.netWeight || 0) * 1) +
            scope.row.fee1 * 1 +
            scope.row.fee2 * 1 +
            scope.row.tip * 1 +
            (scope.row.checkPrice || 0) * 1
          if (treceivable < 0) {
            treceivable = 0
          }
        } else {
          treceivable = (scope.row.checkPrice || 0) * 1 + scope.row.treceivable * 1
        }
        treceivable = treceivable.toFixed(2)
        // let tempAccReceivable = 0
        // if (this.order.payStatus > 1) {
        //   tempAccReceivable = scope.row.accReceivable
        // } else {
        //   tempAccReceivable = treceivable
        // }
        scope.row.treceivable = treceivable
        // scope.row.accReceivable = tempAccReceivable
        if (scope.row.pricingMode === 2) {
          if (!scope.row.gasWeight || scope.row.gasWeight * 1 <= 0) {
            this.$message.warning('请填写送出重量')
            return
          }
          if (scope.row.accReceivable === '' || scope.row.accReceivable == null) {
            this.$message.warning('请填写实收金额')
            return
          }
          if (!scope.row.specCode) {
            this.$message.warning('请选择规格')
            return
          }
        }
        this.$set(scope.row, '_edit', false)
        this.$set(
          this.tableData.defaultData,
          scope.$index,
          JSON.parse(JSON.stringify(scope.row))
        )
        this.$set(this.tableData.data, scope.$index, JSON.parse(JSON.stringify(scope.row)))
      },
      handleCancle(scope) {
        this.$set(
          this.tableData.data,
          scope.$index,
          JSON.parse(JSON.stringify(this.tableData.defaultData[scope.$index]))
        )
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.temp.orgId = value.orgId
        this.currentOrg = value
        this.temp.userId = ''
        // this.getOwnerList()
        this.getOwnersListNew()
        this.temp.paymentMethod = ''
        this.removePaymentMethod()
      },
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if ([0, 7, 8, 9, 10, 11].includes(index)) {
            sums[index] = ''
            return
          }
          if (index === 1) {
            sums[index] = '合计'
            return
          }
          const values = data.map((item) => Number(item[column.property]))
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          }
        })
        sums[4] = isNaN(sums[4]) ? '0.00' : sums[4].toFixed(2)
        sums[5] = isNaN(sums[5]) ? '0.00' : sums[5].toFixed(2)
        sums[6] = isNaN(sums[6]) ? '' : sums[6].toFixed(2)
        sums[12] = isNaN(sums[12]) ? '' : sums[12].toFixed(2)
        sums[13] = isNaN(sums[13]) ? '' : sums[13].toFixed(2)
        this.sums = sums
        return sums
      },
      reset() {
        this.visible = false
        this.currentOrg = null
        this.tableData.data = []
        this.tableData.defaultData = []
        this.showCsmCard = false
        this.order = {}
        this.temp = {
          orgSNNo: '',
          userId: '',
          paymentMethod: 1
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.table {
  /deep/ .cell .right {
    display: inline-block;
    width: 100%;
    text-align: right;
  }
  /deep/ .el-input-number {
    width: 88px;
    padding-right: 5px;
    padding-left: 5px;
  }
}
</style>
